import React, { useState, useEffect, useCallback } from 'react';
import { Button, Table, Modal, Form, Input, notification } from 'antd';
import { fetchApi } from '../../general/api';

interface Project {
    project_id: number;
    project_name: string;
    project_code: string;
    project_instruction: string;
}

const ManageProject: React.FC = () => {
    const [projectList, setProjectList] = useState<Project[]>([]); // 项目列表
    const [selectedRows, setSelectedRows] = useState<Project[]>([]); // 选中行
    const [isEditMode, setIsEditMode] = useState(false); // 编辑模式状态
    const [isModalOpen, setIsModalOpen] = useState(false); // 弹框显示状态
    const [form] = Form.useForm(); // 表单实例

    // 表格列定义
    const getTableColumns = () => [
        { title: '项目名', dataIndex: 'project_name', key: 'project_name', width: 150 },
        { title: '项目编码', dataIndex: 'project_code', key: 'project_code', width: 150 },
        { title: '项目介绍', dataIndex: 'project_instruction', key: 'project_instruction', width: 150 },
    ].map((col) => ({
        ...col,
        ellipsis: true,
        render: (text: string | React.ReactNode) => (
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block' }}>
                {text}
            </span>
        ),
    }));

    // 获取项目列表数据
    const fetchProjectList = useCallback(async () => {
        try {
            const response_data = await fetchApi('/easymonitor/api/project', {
                method: 'GET',
            });
            setProjectList(response_data);
        } catch (error) {
            notification.error({
                message: '请求失败',
                description: `获取项目列表失败: ${error}`,
                duration: 2,
            });
        }
    }, []); // 空数组表明 fetchApi 和其他依赖是稳定的

    // 显示通知
    const showNotification = (type: 'success' | 'error' | 'warning', message: string, description: string) => {
        notification[type]({ message, description, duration: 2 });
    };

    // 打开新增/编辑弹框
    const openModal = (record: Project | null = null) => {
        setIsModalOpen(true);
        setIsEditMode(!!record);

        setTimeout(() => {
            if (record) {
                form.setFieldsValue(record);
            } else {
                form.resetFields();
            }
        }, 0); // 确保表单已渲染后再调用
    };


    // 关闭弹框
    const closeModal = () => {
        setIsModalOpen(false);
        form.resetFields();
    };

    // 提交表单
    const handleSubmit = async (values: Project) => {
        try {
            const method = isEditMode ? 'PUT' : 'POST';
            const endpoint = '/easymonitor/api/project';
            const successMessage = isEditMode ? '项目编辑成功' : '项目新增成功';

            await fetchApi(endpoint, {
                method,
                body: JSON.stringify({ ...values, project_id: isEditMode ? selectedRows[0]?.project_id : undefined }),
            });

            showNotification('success', successMessage, successMessage);
            fetchProjectList();
            closeModal();
            setSelectedRows([]);
        } catch (error) {
            showNotification('error', '提交失败', `操作失败: ${error}`);
        }
    };

    // 删除选中的项目
    const handleDelete = async () => {
        if (selectedRows.length === 0) {
            showNotification('warning', '警告', '请选择至少一条记录进行删除！');
            return;
        }

        Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${selectedRows.length} 个项目吗？`,
            onOk: async () => {
                try {
                    await fetchApi('/easymonitor/api/project', {
                        method: 'DELETE',
                        body: JSON.stringify(selectedRows),
                    });

                    showNotification('success', '删除成功', '选中的项目已成功删除。');
                    fetchProjectList();
                    setSelectedRows([]);
                } catch (error) {
                    showNotification('error', '删除失败', `删除操作失败: ${error}`);
                }
            },
        });
    };

    // 初始化加载数据
    useEffect(() => {
        fetchProjectList();
    }, [fetchProjectList]); // 将 fetchProjectList 添加到依赖数组

    return (
        <div style={{ display: 'flex', flexDirection: 'column', minHeight: '700px' }}>
            {/* 按钮区 */}
            <div style={{ marginBottom: '16px', display: 'flex', gap: '8px' }}>
                <Button type="primary" onClick={() => openModal()}>新增</Button>
                <Button
                    onClick={() => {
                        if (selectedRows.length !== 1) {
                            showNotification('warning', '警告', '请选择一条记录进行编辑！');
                        } else {
                            openModal(selectedRows[0]);
                        }
                    }}
                >
                    编辑
                </Button>
                <Button danger onClick={handleDelete}>删除</Button>
            </div>

            {/* 表格区 */}
            <Table
                size="small"
                columns={getTableColumns()}
                dataSource={projectList}
                rowKey="project_id"
                pagination={{ position: ['bottomCenter'], pageSize: 12 }}
                rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: selectedRows.map((row) => row.project_id),
                    onChange: (_, rows) => setSelectedRows(rows),
                }}
                onRow={(record) => ({
                    onClick: () => {
                        const isSelected = selectedRows.some((row) => row.project_id === record.project_id);
                        const updatedRows = isSelected
                            ? selectedRows.filter((row) => row.project_id !== record.project_id)
                            : [...selectedRows, record];
                        setSelectedRows(updatedRows);
                    },
                })}
                style={{ overflowX: 'auto' }}
                locale={{ emptyText: '暂无数据' }}
            />


            {/* 新增/编辑弹框 */}
            <Modal
                title={isEditMode ? '编辑项目' : '新增项目'}
                open={isModalOpen}
                onOk={() => form.submit()}
                onCancel={closeModal}
                destroyOnClose
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                    onFinishFailed={() => showNotification('warning', '表单验证失败', '请填写必填字段！')}
                >
                    <Form.Item
                        label="项目名"
                        name="project_name"
                        rules={[{ required: true, message: '请输入项目名！' }]}>
                        <Input placeholder="请输入项目名" />
                    </Form.Item>
                    <Form.Item
                        label="项目编码"
                        name="project_code"
                        rules={[{ required: true, message: '请输入项目编码！' }]}>
                        <Input placeholder="请输入项目编码" />
                    </Form.Item>
                    <Form.Item label="项目介绍" name="project_instruction">
                        <Input.TextArea placeholder="请输入项目介绍" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ManageProject;
